import cv2
import numpy as np
from PIL import ImageGrab
import time


def detect_view_change_optical_flow():
    # 参数设置
    feature_params = dict(maxCorners=100,
                          qualityLevel=0.3,
                          minDistance=7,
                          blockSize=7)

    lk_params = dict(winSize=(15, 15),
                     maxLevel=2,
                     criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))

    # 创建随机颜色
    color = np.random.randint(0, 255, (100, 3))

    # 初始化前一帧和特征点
    prev_frame = None
    p0 = None

    # 游戏窗口区域
    game_region = (0, 0, 1920, 1080)

    while True:
        # 抓取游戏画面
        img = ImageGrab.grab(bbox=game_region)
        frame = np.array(img)
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        if prev_frame is not None and p0 is not None:
            # 计算光流
            p1, st, err = cv2.calcOpticalFlowPyrLK(prev_frame, gray, p0, None, **lk_params)

            # 选择好的点
            good_new = p1[st == 1]
            good_old = p0[st == 1]

            # 计算平均位移
            if len(good_new) > 10:
                dx = np.mean(good_new[:, 0] - good_old[:, 0])
                dy = np.mean(good_new[:, 1] - good_old[:, 1])

                # 设置阈值
                if abs(dx) > 0.5 or abs(dy) > 0.5:
                    print(f"视角移动: X={dx:.2f}, Y={dy:.2f}")

            # 绘制跟踪点（调试用）
            for i, (new, old) in enumerate(zip(good_new, good_old)):
                a, b = new.ravel()
                c, d = old.ravel()
                frame = cv2.line(frame, (int(a), int(b)), (int(c), int(d)), color[i].tolist(), 2)
                frame = cv2.circle(frame, (int(a), int(b)), 5, color[i].tolist(), -1)

            cv2.imshow('Optical Flow', frame)
            if cv2.waitKey(1) & 0xFF == 27:  # 按ESC退出
                break

        # 更新前一帧和特征点
        prev_frame = gray.copy()
        p0 = cv2.goodFeaturesToTrack(gray, mask=None, **feature_params)

        time.sleep(0.03)  # 约30FPS

    cv2.destroyAllWindows()
